/**
 * Copyright (c) 2015 https://github.com/howiefh
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.tyijian.admin.shiro.realm;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.tyijian.admin.entity.SysRole;
import com.tyijian.admin.entity.SysUser;
import com.tyijian.admin.service.UserService;
import com.tyijian.admin.shiro.token.JsonWebToken;

/**
 *
 *
 * @author howiefh
 */
public class StatelessRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        // 仅支持JsonWebToken类型的Token
        return token instanceof JsonWebToken;
    }

    
    /**
     * shiro 授权处理的业务
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 根据用户名查找角色，请根据需求实现
    	Long userId = (Long) principals.getPrimaryPrincipal();
        SysUser user = userService.get(userId);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        SimplePrincipalCollection principalCollection = (SimplePrincipalCollection) principals;
        principalCollection.clear();
        principalCollection.add(user, getName());
        Set<String> roleNames=new HashSet<String>();
        Set<String> permissions=new HashSet<String>();
        for(SysRole role:user.getRoleList()){
        	roleNames.add(role.getName());
        	for(String str:role.getPermissionList()){
        		permissions.add(str);
        	}
        }
        authorizationInfo.setRoles(roleNames);
        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }

    
    /**
     * 根据token获取认证信息
     * 
     * 验证处理的业务，此处不做处理，交给CredentialsMatcher 处理
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    	
        JsonWebToken jsonWebToken = (JsonWebToken) token;
        String jwt = jsonWebToken.getToken();
        // 然后进行客户端消息摘要和服务器端消息摘要的匹配
        return new SimpleAuthenticationInfo("", jwt, getName());
    }
}